package uclick.messenger.server.action;

import java.io.IOException;
import java.net.Socket;
import java.util.Iterator;
import java.util.Vector;

import org.w3c.dom.Document;

import uclick.messenger.server.chatting.ChattingRoomInfo;
import uclick.messenger.server.chatting.MessangerUserInfo;
import uclick.messenger.server.chatting.ServerChattingManager;
import uclick.messenger.server.dto.MemberDto;
import uclick.messenger.server.xml.ServerXMLConvertor;

public class RequestFileTransferInitAction implements Action {
	/**
	 * Logger for this class
	 */
	@Override
	public void excute(Socket socket, Document document) {
		System.out.println("oooooooo");
		ServerXMLConvertor convertor = new ServerXMLConvertor();
		ServerChattingManager chattingManager = ServerChattingManager.getChattingManager();
		MessangerUserInfo userInfo = MessangerUserInfo.getUserInfo();
		try {
			String roomnum = convertor.getContent(document, "roomnum");
			Vector<MemberDto> receiverlist = new Vector<MemberDto>(5, 5);
			Vector<String> receivers = convertor.getContentList(document,"receiver");
			System.out.println("size : "+receivers.size());
			if(roomnum.equals("-1")){
				//1:1
				System.out.println("1:1");
				Iterator<String> iter = receivers.iterator();
				while (iter.hasNext()) {
					String id = (String) iter.next();
					MemberDto receiver = userInfo.findUser(id);
					receiverlist.add(receiver);
				}
			}else{
				ChattingRoomInfo roomInfo = chattingManager.findChattingRoom(Integer.parseInt(roomnum));
				receiverlist = roomInfo.getUserList();
				String sender = convertor.getContent(document, "sender");
				
				for(int i = 0 ; i < roomInfo.getUserList().size();i++){
					if(!roomInfo.getUserList().get(i).equals(sender)){
						receiverlist.add(roomInfo.getUserList().get(i));
					}
				}
			}
			
			String res = convertor.toXML(document,"xml/file/file_transfer_init.dtd");
			System.out.println("xml:"+res);
			for (int i = 0; i < receiverlist.size(); i++) {
				convertor.responseWriter(res, receiverlist.get(i).getSocket());
			}
		} catch (NullPointerException e) {
			System.out.println("size null");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
